定義好單一元件 (template+區域樣式),在畫面內引入元件,並根據需求再做調整如:樣板迴圈 v-for、傳資料回元件。不將資料寫在小元件內,是避免後續又有其他頁面需要用到此元件時,裡面會有不必要的資料。
script 設定 props 等待資料從外層傳回來。
Stickers.vue*
<template>
<div>
<div class="img-center">
...
</div>
<div class="text">
<h3>{{ spotName }}</h3>
<img src="../assets/location.svg"><span>{{ spotLocation }}</span>
</div>
</div>
</template>
<script>
export default {
name: "Stickers",
props: ['spotName', 'spotLocation']
}
</script>
<style scoped lang="scss">
...
</style>
Home.vue*
<template>
<div>
<stickers v-for="(spot, index) in hotSpots"
:spot-name="hotSpots[index].name"
:spot-location="hotSpots[index].location">
</stickers>
</div>
</template>
<script>
import Stickers from "@/components/Stickers.vue";
export default {
name: 'Home',
data: ()=> ({
hotSpots: [
{ name:'花園夜市', location: '台南市' },
{ name:'孔廟', location: '台南市' },
{ name:'101大樓', location: '台北市' },
{ name:'象山', location: '台北市' }
]
}),
components: {
Stickers
}
}
</script>
資料來源:
https://www.youtube.com/watch?v=W2j7CjQI2y4&t=340s
https://book.vue.tw/CH2/2-2-communications.html
https://medium.com/pierceshih/vue-js-學習筆記-day6-v-for-列表渲染-基礎篇-79fb79d5fcb